package com.tanhua.manager.interceptors;

import com.tanhua.domain.db.Admin;
import com.tanhua.manager.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       进入到方法之前拦截
//        从token中获取 用户user  放到ThreadLocal中
        String token = request.getHeader("Authorization");
		//        把页面上带过来的token中的“Bearer ”去掉
        token = token.replace("Bearer ","");
        if(token==null){
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return false;
        }
        Admin admin = adminService.findAdminByToken(token);
		admin.setToken(token);
        AdminHolder.setAdmin(admin);

        return true;// 代表拦截  true:放行
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        方法执行完成后，把ThreadLocal中的数据删除，不然数据多了会造成内存溢出
        AdminHolder.removeAdmin();
    }
}
